// pages/purchase/purchase.js
const http = require('../../utils/http')
const api = require('../../utils/api')
const ui = require('../../utils/ui')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    purchaseInfo: {},
    selected: 0,
    value: 0,
    screenWidth: 0,
  },

  itemSelected(event){
    let index = event.currentTarget.dataset.index
    this.setData({
      selected: index,
      value: this.data.purchaseInfo.recharge[index].recharge,
    })
  },

  getData() {
    http.request({
      url: api.purchaseActivity,
      data: {
        memberId: getApp().globalData.memberId,
      },
    }).then(res=> {
      console.log(res)
      let data = res.data.result
      if (data != null) {
        this.setData({
          value: data.recharge [this.data.selected].recharge,
          purchaseInfo: data
        })
      }
    })
  },

  purchaseWallet() {
    let item = this.data.purchaseInfo.recharge[this.data.selected]
    http.request({
      url: api.purchaseWallet,
      method: "POST",
      data: {
        memberId: getApp().globalData.memberId,
        recharge: item.recharge,
        gift: item.gift
      },
    }).then(res=> {
      console.log(res)
      let prepayObj = res.data.result.prepayVO
      // prepayObj.package = "prepay_id="+prepayObj.prepayId
      prepayObj.package = prepayObj.packages
      prepayObj.signType = "RSA"
      prepayObj.timeStamp += ""
      console.log("prepayObj", prepayObj)
      try {
        // 得到接口返回的数据，向微信发起支付
        wx.requestPayment({
          ...prepayObj,
          success:(res)=>{
            ui.showToast({
              title: "支付成功",
            });
            console.log("支付结果：", res);
            wx.navigateBack({
              delta: 0,
            })
          },
          fail:(res)=>{
            console.log("支付失败", res)
          },
          complete:(res)=>{
            console.log("支付完成", res)
          }
        });
      } catch (err) {
        ui.showToast({
          title: "支付失败",
        });
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getData()
    let screenWidth = getApp().globalData.screenWidth;
    this.setData({
      screenWidth: screenWidth,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})